#                               第十节、从文件读取数据
# 1、读取文件中所有数据  read()
with open('D:/stream/hello.java') as f:
    c = f.read()
print(c)
'''
Hello World .Hello World .
9
'''
filename = 'D:/stream/hello.java'
with open(filename) as f:
    c = f.read()
print(c.strip())  # 删除首尾空白

# 2、逐行读取
filename = 'D:/stream/world.java'
with open(filename) as f:
    for line in f:
        print(line)
'''
I am luckly!I am luckly!

I am luckly!I am luckly!

I am luckly!I am luckly!
'''
# 3、创建一个包含文件各行内容的列表

filename = 'D:/stream/hello.txt'
with open(filename, encoding='utf-8') as f:  # 指定读取文件的格式
    lines = f.readlines()
for line in lines:
    print(line.strip())
'''
阿萨大大啊飒飒
额外的是
qweq
'''
# 4、使用文件的内容
filename = 'D:/stream/hello.txt'
with open(filename, encoding='utf-8') as f:  # 指定读取文件的格式
    lines = f.readlines()

strs = ''
for line in lines:
    strs += line.strip()
print(strs)
print(len(strs))
'''
阿萨大大啊飒飒额外的是qweq
15
'''
# 二、写入文件
# 1、写入内容
filename = 'D:/stream/world.txt'
with open(filename, 'w') as f:
    f.write('I like speaking .')

# 2、向一个文件写入多行
filename = 'D:/stream/world.txt'
with open(filename, 'w') as f:
    f.write('I like speaking .\n')
    f.write('I like speaking .\n')
# 3、附加内容到文件
filename = 'D:/stream/world.txt'
with open(filename, 'a') as f:
    f.write('I like myself .\n')
    f.write('I like myself .\n')

# 三、异常

# 1、处理异常
try:
    print(5 / 0)
except ZeroDivisionError:
    print('Erro')

# 2、else代码块
try:
    m = 5 / 1
except ZeroDivisionError:
    print('Erro')
else:
    print(m)
    print


# 3、使用多个文件

def count_words(filename):
    with open(filename, encoding='utf-8') as f:
        coent = f.read()
        word = coent.split()
        print(filename, '中单词个数：', len(word))


ls = ['D:/stream/hello.txt', 'D:/stream/world.txt']
for filename in ls:
    count_words(filename)

'''
D:/stream/hello.txt 中单词个数： 3
D:/stream/world.txt 中单词个数： 16
'''

# 四、存储数据
# 1、存储数
import json

m = [1, 2, 3, 4]
filename = 'D:/stream/number.json'
with open(filename, 'w') as f:
    json.dump(m, f)

# 1、读取数

import json

filename = 'D:/stream/number.json'

with open(filename) as f:
    numbers = json.load(f)
print(numbers)
